//
//  NSString+BXExtension.m
//  BXInsurenceBroker
//
//  Created by JYJ on 16/2/23.
//  Copyright © 2016年 baobeikeji. All rights reserved.
//

#import "NSString+BXExtension.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (BXExtension)


- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize {
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
//仅显示前4后4
-(NSString*)getShelterIDCard{
    if (self.length<8) {
        return self;
    }
    NSString * finalStr = [self stringByReplacingCharactersInRange:NSMakeRange(4, self.length-8) withString:@" **** **** "];
    return finalStr;
}
//仅显示前4后3
-(NSString*)getShelterBankCard{
    if (self.length<7) {
        return self;
    }
    NSString * finalStr = [self stringByReplacingCharactersInRange:NSMakeRange(4, self.length-7) withString:@" **** **** "];
    return finalStr;
}
//仅显示前3后4
-(NSString*)getShelterPhoneNum{
    if (self.length<7) {
        return self;
    }
    NSString * finalStr = [self stringByReplacingCharactersInRange:NSMakeRange(3, self.length-7) withString:@" **** "];
    return finalStr;
}
//姓名 多个字只显示前1后1,2个字仅显示后1
-(NSString*)getShelterName{
    if (self.length<=1) {
        return self;
    }
    if (self.length==2) {
        NSString * finalStr = [self stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"*"];
        return finalStr;
    }else{
        NSString * rangeStr = [self substringWithRange:NSMakeRange(1, self.length-2)];
        NSString * starStr = @"";
        for (int i =0; i<self.length-2; i++) {
            starStr = [NSString stringWithFormat:@"%@*",starStr];
        }
        NSString * finalStr = [self stringByReplacingOccurrencesOfString:rangeStr withString:starStr];
        return finalStr;
    }
}
#pragma mark - 检测字符串是否为空
-(BOOL)xhq_notNULL {
    if ([self isEqual:[NSNull null]] ||
        [self isKindOfClass:[NSNull class]] ||
        [self isEqualToString:@"(null)"] ||
        !self) {
        return NO;
    }
    return YES;
}

//6~20位密码 字母数字
-(BOOL)pswFormatCheck {
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    return [self predicateMatches:regex];
}

//身份证
-(BOOL)idFormatCheck{
    NSString *regex = @"\\d{18}$|(\\d{17}[xX])$";
    return [self predicateMatches:regex];
}

//邮箱检测
-(BOOL)emailFormatCheck {
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$";
    return [self predicateMatches:regex];
}

//银行卡检测
-(BOOL)bankCardFormatCheck {
    //NSString *regex2 = @"^(\\d{15,30})";
    if (!self || [self isKindOfClass:[NSNull class]] || self.length == 0) {
        return NO;
    }
    
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[self length];
    int lastNum = [[self substringFromIndex:cardNoLength-1] intValue];
    
    NSString *cardNo = [self substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}

//中文检测
-(BOOL)isChinese {
    NSString * regex = @"^[\u4E00-\u9FA5]*$";
    return [self predicateMatches:regex];
}

//正则检测
- (BOOL)predicateMatches:(NSString *)regex {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicate evaluateWithObject:self];
}
//正则去除标签
-(NSString *)getStrWithoutHtml{
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n"
                                                                                    options:0
                                                                                      error:nil];
    NSString * string=[regularExpretion stringByReplacingMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length) withTemplate:@""];
    return string;
}
-(NSMutableArray *)getNumberFromText{
    NSString * regulaStr = @"[0-9]{6,100}";
    NSError*error;
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSMutableArray * regexArr = [NSMutableArray new];
    if (!error) {
        NSArray*arrayOfAllMatches = [regex matchesInString:self options:NSMatchingReportCompletion range:NSMakeRange(0, [self length])];

        for(NSTextCheckingResult*match in arrayOfAllMatches){
            NSString* substringForMatch = [self substringWithRange:match.range];
            [regexArr addObject:substringForMatch];
        }
    }
    return regexArr;
}
-(BOOL)isPicture{
    NSArray * arr = [self componentsSeparatedByString:@"."];
    if (arr.count > 0) {
        NSString * fix = arr.lastObject;
        NSArray * target = @[@"png",@"jpg",@"gif",@"jpeg",@"webp"];
        BOOL isFind = NO;
        for (NSString * key  in target) {
            if ([[fix lowercaseString] isEqualToString:key]) {
                isFind = YES;
                break;
            }
        }
        return isFind;
    }
    return NO;
}
-(BOOL)isPureInt{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
-(BOOL)isPureFloat{
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
-(BOOL)isEnglish{
    NSString *emailRegex = @"[A-Za-z]$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}
-(NSString*)returnDecimalNumStr{
    NSString *doubleString  = [NSString stringWithFormat:@"%lf", [self doubleValue]];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}

-(BOOL)hasIllegalCharacter{
    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:self]) {
        return YES;
    }
    return NO;
}

-(BOOL)verifyURL{
    NSString *pattern = @"^(((http[s]{0,1}|ftp|Http[s]{0,1})://)?[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:self];
}
-(NSString *)string2MD5{
    NSString *resultStr = nil;//加密后的结果
    const char *cStr = [self UTF8String];//指针不能变，cStr指针变量本身可以变化
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    resultStr = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                 result[0], result[1], result[2], result[3],
                 result[4], result[5], result[6], result[7],
                 result[8], result[9], result[10], result[11],
                 result[12], result[13], result[14], result[15]
                 ];
    return resultStr;
}
-(BOOL)isTel{
    NSString *telRegex = @"^0\\d{2,3}-\\d{7,8}$";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    return [telTest evaluateWithObject:self];
}
-(NSString *)urlEncodedString{
    NSString *string = self;
    NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)string,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}
-(NSString *)urlLDecodedString{
    NSString *string = self;
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)string, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}
-(BOOL)isContainsString:(NSString *)string{
    if(string == nil) return NO;
    return [self rangeOfString:string].location != NSNotFound;
}
/*
 *  设置行间距和字间距
 *
 *  @param string    字符串
 *  @param lineSpace 行间距
 *  @param kern      字间距
 *  @param font      字体大小
 *
 *  @return 富文本
 */
- (NSAttributedString *)getAttributedWithLineSpace:(CGFloat)lineSpace kern:(CGFloat)kern font:(UIFont *)font{
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    //调整行间距
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attriDict = @{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern),
        NSFontAttributeName:font};
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:self attributes:attriDict];
    return attributedString;
}
- (NSString *)base64EncodedString
{
    NSData *data = [self dataUsingEncoding: NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

- (NSString *)base64DecodedString
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];
    return [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];
}
@end
